<template>
  <div class="compact-search-demo">
    <el-card>
      <template #header>
        <div class="demo-header">
          <span>紧凑型搜索表单演示</span>
          <div class="demo-controls">
            <el-button @click="addMockData" size="small">添加模拟数据</el-button>
            <el-button @click="clearData" size="small">清空数据</el-button>
          </div>
        </div>
      </template>

      <!-- 紧凑型搜索表单 -->
      <div class="search-form">
        <div class="search-form-header">
          <h3 class="search-title">
            <el-icon><Search /></el-icon>
            实时搜索演示
          </h3>
          <el-button 
            text 
            type="primary" 
            @click="toggleSearchForm"
            class="toggle-btn"
          >
            {{ searchFormCollapsed ? '展开' : '收起' }}
            <el-icon class="toggle-icon" :class="{ 'is-collapsed': searchFormCollapsed }">
              <ArrowDown />
            </el-icon>
          </el-button>
        </div>
        
        <el-collapse-transition>
          <div v-show="!searchFormCollapsed" class="search-form-content">
            <el-form :model="searchForm" class="search-form-inner">
              <el-row :gutter="16">
                <el-col :xs="24" :sm="12" :md="8" :lg="6">
                  <el-form-item label="关键词搜索">
                    <el-input
                      v-model="searchForm.search"
                      placeholder="请输入关键词"
                      clearable
                      prefix-icon="Search"
                      class="search-input"
                    />
                  </el-form-item>
                </el-col>
                
                <el-col :xs="24" :sm="12" :md="8" :lg="6">
                  <el-form-item label="类型">
                    <el-select 
                      v-model="searchForm.type" 
                      placeholder="请选择类型" 
                      clearable 
                      class="search-select"
                    >
                      <el-option label="类型A" value="typeA" />
                      <el-option label="类型B" value="typeB" />
                      <el-option label="类型C" value="typeC" />
                    </el-select>
                  </el-form-item>
                </el-col>
                
                <el-col :xs="24" :sm="12" :md="8" :lg="6">
                  <el-form-item label="状态">
                    <el-select 
                      v-model="searchForm.status" 
                      placeholder="请选择状态" 
                      clearable 
                      class="search-select"
                    >
                      <el-option label="活跃" value="active" />
                      <el-option label="暂停" value="paused" />
                      <el-option label="完成" value="completed" />
                    </el-select>
                  </el-form-item>
                </el-col>
                
                <el-col :xs="24" class="search-actions-col">
                  <el-form-item class="search-actions">
                    <el-button type="primary" @click="handleSearch">
                      <el-icon><Search /></el-icon>
                      搜索
                    </el-button>
                    <el-button @click="handleReset">
                      <el-icon><RefreshLeft /></el-icon>
                      重置
                    </el-button>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
          </div>
        </el-collapse-transition>
      </div>

      <!-- 数据列表 -->
      <div class="data-list">
        <div class="list-header">
          <span>搜索结果 ({{ filteredData.length }}/{{ mockData.length }})</span>
          <el-tag v-if="hasActiveFilters" type="info" size="small">
            已应用筛选条件
          </el-tag>
        </div>
        
        <el-table
          :data="filteredData"
          size="small"
          stripe
          style="width: 100%"
        >
          <el-table-column prop="name" label="名称" min-width="150" />
          <el-table-column prop="type" label="类型" width="100">
            <template #default="{ row }">
              <el-tag :type="getTypeTagType(row.type)" size="small">
                {{ getTypeText(row.type) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态" width="100">
            <template #default="{ row }">
              <el-tag :type="getStatusTagType(row.status)" size="small">
                {{ getStatusText(row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="description" label="描述" min-width="200" />
          <el-table-column label="操作" width="120">
            <template #default="{ row }">
              <el-button size="small" @click="handleView(row)">查看</el-button>
              <el-button size="small" type="primary" @click="handleEdit(row)">编辑</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 搜索统计 -->
      <div class="search-stats">
        <el-descriptions :column="4" size="small" border>
          <el-descriptions-item label="总数据">{{ mockData.length }}</el-descriptions-item>
          <el-descriptions-item label="筛选结果">{{ filteredData.length }}</el-descriptions-item>
          <el-descriptions-item label="筛选率">{{ filterRate }}%</el-descriptions-item>
          <el-descriptions-item label="搜索关键词">{{ searchForm.search || '无' }}</el-descriptions-item>
        </el-descriptions>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { Search, ArrowDown, RefreshLeft } from '@element-plus/icons-vue'

// 响应式数据
const searchFormCollapsed = ref(false)
const mockData = ref<any[]>([])

// 搜索表单
const searchForm = reactive({
  search: '',
  type: '',
  status: ''
})

// 计算属性
const filteredData = computed(() => {
  if (!mockData.value.length) return []
  
  return mockData.value.filter(item => {
    // 关键词搜索
    if (searchForm.search) {
      const searchText = searchForm.search.toLowerCase()
      const nameMatch = item.name.toLowerCase().includes(searchText)
      const descMatch = item.description.toLowerCase().includes(searchText)
      if (!nameMatch && !descMatch) return false
    }
    
    // 类型筛选
    if (searchForm.type && item.type !== searchForm.type) {
      return false
    }
    
    // 状态筛选
    if (searchForm.status && item.status !== searchForm.status) {
      return false
    }
    
    return true
  })
})

const hasActiveFilters = computed(() => {
  return !!(searchForm.search || searchForm.type || searchForm.status)
})

const filterRate = computed(() => {
  if (!mockData.value.length) return 0
  return Math.round((filteredData.value.length / mockData.value.length) * 100)
})

// 方法
const toggleSearchForm = () => {
  searchFormCollapsed.value = !searchFormCollapsed.value
}

const handleSearch = () => {
  ElMessage.success('搜索功能已触发（实时搜索已自动生效）')
}

const handleReset = () => {
  searchForm.search = ''
  searchForm.type = ''
  searchForm.status = ''
  ElMessage.info('搜索条件已重置')
}

const addMockData = () => {
  const types = ['typeA', 'typeB', 'typeC']
  const statuses = ['active', 'paused', 'completed']
  const names = ['项目Alpha', '任务Beta', '计划Gamma', '方案Delta', '系统Epsilon']
  
  for (let i = 0; i < 10; i++) {
    mockData.value.push({
      id: mockData.value.length + 1,
      name: `${names[i % names.length]} ${mockData.value.length + 1}`,
      type: types[Math.floor(Math.random() * types.length)],
      status: statuses[Math.floor(Math.random() * statuses.length)],
      description: `这是第 ${mockData.value.length + 1} 个项目的详细描述信息`
    })
  }
  ElMessage.success(`已添加 10 条模拟数据，当前总数：${mockData.value.length}`)
}

const clearData = () => {
  mockData.value = []
  ElMessage.info('已清空所有数据')
}

const handleView = (row: any) => {
  ElMessage.info(`查看项目：${row.name}`)
}

const handleEdit = (row: any) => {
  ElMessage.info(`编辑项目：${row.name}`)
}

// 辅助方法
const getTypeText = (type: string) => {
  const map: Record<string, string> = {
    typeA: '类型A',
    typeB: '类型B',
    typeC: '类型C'
  }
  return map[type] || type
}

const getTypeTagType = (type: string): 'primary' | 'success' | 'warning' | 'info' | 'danger' => {
  const map: Record<string, 'primary' | 'success' | 'warning' | 'info' | 'danger'> = {
    typeA: 'primary',
    typeB: 'success',
    typeC: 'warning'
  }
  return map[type] || 'info'
}

const getStatusText = (status: string) => {
  const map: Record<string, string> = {
    active: '活跃',
    paused: '暂停',
    completed: '完成'
  }
  return map[status] || status
}

const getStatusTagType = (status: string): 'primary' | 'success' | 'warning' | 'info' | 'danger' => {
  const map: Record<string, 'primary' | 'success' | 'warning' | 'info' | 'danger'> = {
    active: 'success',
    paused: 'warning',
    completed: 'info'
  }
  return map[status] || 'info'
}
</script>

<style lang="scss" scoped>
.compact-search-demo {
  .demo-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .search-form {
    margin-bottom: 12px;
    background: var(--bg-color-light);
    border: 1px solid var(--border-color-light);
    border-radius: 8px;
    overflow: hidden;

    .search-form-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 8px 16px;
      background: var(--fill-color-light);
      border-bottom: 1px solid var(--border-color-extra-light);

      .search-title {
        margin: 0;
        font-size: 14px;
        font-weight: 600;
        color: var(--text-color-primary);
        display: flex;
        align-items: center;
        gap: 6px;

        .el-icon {
          color: var(--color-primary);
          font-size: 16px;
        }
      }

      .toggle-btn {
        font-size: 12px;
        padding: 4px 8px;

        .toggle-icon {
          transition: transform 0.3s ease;
          font-size: 12px;

          &.is-collapsed {
            transform: rotate(-90deg);
          }
        }
      }
    }

    .search-form-content {
      padding: 12px 16px;
    }

    .search-form-inner {
      .el-form-item {
        margin-bottom: 8px;

        :deep(.el-form-item__label) {
          font-size: 12px;
          line-height: 1.2;
          margin-bottom: 4px;
        }
      }

      .search-input,
      .search-select {
        :deep(.el-input) {
          --el-input-height: 28px;
        }
        
        :deep(.el-select) {
          --el-select-input-height: 28px;
        }
      }

      .search-actions {
        display: flex;
        gap: 8px;

        .el-button {
          height: 28px;
          padding: 0 12px;
          font-size: 12px;
        }
      }
    }
  }

  .data-list {
    .list-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 8px;
      font-size: 14px;
      color: var(--text-color-primary);
    }

    :deep(.el-table) {
      --el-table-row-height: 40px;
      --el-table-header-height: 36px;
      font-size: 13px;
    }
  }

  .search-stats {
    margin-top: 12px;
  }
}
</style>
